-- Variables
SalvagingWindow = {}

SalvagingWindow.windowName = "SalvagingWindow"
SalvagingWindow.numStats = 0

SalvagingWindow.radioButtons = {}
SalvagingWindow.selectedStat = 0
SalvagingWindow.selectedSlot = 0
SalvagingWindow.selectedBackpack = 0
SalvagingWindow.salvagingType = 0

-- Constants
SalvagingWindow.STAT_X_OFFSET = 20
SalvagingWindow.STAT_Y_OFFSET = 30
SalvagingWindow.TITLE_BAR_OFFSET = 30
SalvagingWindow.STAT_RADIO_BUTTON_HEIGHT_OFFSET = SalvagingWindow.TITLE_BAR_OFFSET
SalvagingWindow.WINDOW_BASE_HEIGHT = 60
SalvagingWindow.WINDOW_WIDTH = 350
SalvagingWindow.STAT_CHOICE_HEIGHT = 67

-- Local Functions 
local function UpdateStatRadioButtons()
    for index, windowName in ipairs( SalvagingWindow.radioButtons )
    do
        local buttonName = SalvagingWindow.windowName.."Stat"..index
        --DEBUG(L"Window Id: "..WindowGetId( buttonName ) )
        if ( SalvagingWindow.selectedStat == WindowGetId( buttonName ) )
        then
            --DEBUG(statStringLookUp[SalvagingWindow.selectedStat]..L" Selected")
            ButtonSetPressedFlag( buttonName.."Button", true )
        else
            --DEBUG(L""..StringToWString(SalvagingWindow.windowName.."Stat"..index.."Button"))
            ButtonSetPressedFlag( buttonName.."Button", false )
        end
    end
end

local function AddSalvageStat( stat, statString )
    SalvagingWindow.numStats = SalvagingWindow.numStats + 1

    local buttonWindowName = SalvagingWindow.windowName.."Stat"..SalvagingWindow.numStats
    --DEBUG(L"SalvagingWindow.numStats: "..SalvagingWindow.numStats)
    -- create the window
    CreateWindowFromTemplate( buttonWindowName, "EA_Window_SalvagingRadioButtonTemplate", SalvagingWindow.windowName )
    
    -- Anchor the radio button and set its text + id
    local xOffset = SalvagingWindow.STAT_X_OFFSET
    local yOffset = SalvagingWindow.STAT_Y_OFFSET * SalvagingWindow.numStats + SalvagingWindow.STAT_RADIO_BUTTON_HEIGHT_OFFSET
    WindowAddAnchor( buttonWindowName, "topleft", SalvagingWindow.windowName, "topleft", xOffset, yOffset )
    LabelSetText( buttonWindowName.."Label", statString )
    WindowSetId( buttonWindowName, stat )
    
    SalvagingWindow.radioButtons[SalvagingWindow.numStats] = buttonWindowName
end

local function DestroySalvageStats()
    for index, windowName in ipairs( SalvagingWindow.radioButtons )
    do
        WindowClearAnchors( windowName )
        DestroyWindow( windowName )
    end
    
    SalvagingWindow.radioButtons = {}
    SalvagingWindow.numStats = 0
    SalvagingWindow.selectedStat = 0
    SalvagingWindow.selectedSlot = 0
    SalvagingWindow.selectedBackpack = 0
    SalvagingWindow.salvagingType = 0
end

-- SalvigingWindow Funcitons
function SalvagingWindow.BeginSalvage()
    SetDesiredInteractAction( SystemData.InteractActions.SALVAGE )
end

function SalvagingWindow.EndSalvage()
    if( GetDesiredInteractAction() == SystemData.InteractActions.SALVAGE )
    then
        SetDesiredInteractAction( SystemData.InteractActions.NONE )
    end
end

function SalvagingWindow.Initialize()
    RegisterEventHandler( SystemData.Events.L_BUTTON_DOWN_PROCESSED, "SalvagingWindow.OnLButtonProcessed")
    RegisterEventHandler( SystemData.Events.R_BUTTON_DOWN_PROCESSED, "SalvagingWindow.OnRButtonProcessed")
    LabelSetText(SalvagingWindow.windowName.."TitleBarText", GetString( StringTables.Default.LABEL_SKILL_SALVAGING ) )
    LabelSetText(SalvagingWindow.windowName.."ChoiceText", GetString( StringTables.Default.TEXT_CAN_BE_SALVAGED_INTO ) )
    ButtonSetText( SalvagingWindow.windowName.."Accept", GetString( StringTables.Default.TEXT_ACCEPT_SALVAGING ) )
    local _, choiceHeight = LabelGetTextDimensions( SalvagingWindow.windowName.."ChoiceText" )
    SalvagingWindow.STAT_RADIO_BUTTON_HEIGHT_OFFSET  = SalvagingWindow.TITLE_BAR_OFFSET + choiceHeight
end

function SalvagingWindow.Shutdown()
    UnregisterEventHandler( SystemData.Events.L_BUTTON_DOWN_PROCESSED, "SalvagingWindow.OnLButtonProcessed")
    UnregisterEventHandler( SystemData.Events.R_BUTTON_DOWN_PROCESSED, "SalvagingWindow.OnRButtonProcessed")
    DestroySalvageStats()
end

function SalvagingWindow.Show()
    if( WindowGetShowing( SalvagingWindow.windowName ) )
    then
        return
    end
    
    WindowSetShowing( SalvagingWindow.windowName, true)
    
    WindowUtils.AddToOpenList( SalvagingWindow.windowName, SalvagingWindow.Hide, WindowUtils.Cascade.MODE_NONE )

    Sound.Play( Sound.WINDOW_OPEN )
end

function SalvagingWindow.Hide()
    if( not WindowGetShowing( SalvagingWindow.windowName ) )
    then
        return
    end

    WindowSetShowing( SalvagingWindow.windowName, false )
    
    Sound.Play( Sound.WINDOW_CLOSE )
    
    WindowUtils.RemoveFromOpenList( SalvagingWindow.windowName )
end

function SalvagingWindow.IsSalvagableItem( itemData )
	return (itemData.flags[GameData.Item.EITEMFLAG_MAGICAL_SALVAGABLE] == true) -- or (itemData.flags[GameData.Item.EITEMFLAG_MUNDANE_SALVAGABLE]
end

function SalvagingWindow.CurrentlyInSalvageMode()
	return GetDesiredInteractAction() == SystemData.InteractActions.SALVAGE
end

function SalvagingWindow.PlayerHasSufficientSkillToSalvageItem( itemData )
    local difficultyClass = GetSalvagingDifficulty( itemData.iLevel )
    return( difficultyClass ~= GameData.Salvaging.IMPOSSIBLE )
end


-- returns a string telling how easy this item is to salvage, along with the string's con color
-- NOTE: this function does not verify the item is salvagable
function SalvagingWindow.GetSalvagingDifficultyForItem( itemData )
    
    local difficultyClass, difficultyPercent = GetSalvagingDifficulty( itemData.iLevel )
    local difficultyString = CraftingUtils.SalvagingDifficulty[difficultyClass].string
    
	local text = GetStringFormatFromTable( "Default", StringTables.Default.TEXT_SALVAGING_DIFFICULTY_FORMAT_STRING, { difficultyString, L""..difficultyPercent } )
	
	return text, CraftingUtils.SalvagingDifficulty[difficultyClass].color
end



function SalvagingWindow.Salvage( slotNum )
    --DEBUG(L"slotNum: "..slotNum)
    local backpackType = EA_BackpackUtilsMediator.GetCurrentBackpackType()
    local inventory = EA_BackpackUtilsMediator.GetItemsFromBackpack( backpackType )
    local itemData = inventory[slotNum]
    if( slotNum == nil or itemData.uniqueID == 0 )
    then
		return
		
	elseif not SalvagingWindow.IsSalvagableItem( itemData )
    then
        TextLogAddEntry( "Chat", SystemData.ChatLogFilters.CRAFTING, GetString( StringTables.Default.TEXT_SALVAGING_ERROR ) )
		Sound.Play( Sound.ACTION_FAILED )
        return

	elseif not SalvagingWindow.PlayerHasSufficientSkillToSalvageItem( itemData )
    then
        TextLogAddEntry( "Chat", SystemData.ChatLogFilters.CRAFTING, GetString( StringTables.Default.TEXT_SALVAGING_FAIL_NOT_ENOUGH_SKILL ) )
		Sound.Play( Sound.ACTION_FAILED )
        return
    end

    -- Get rid the data from the last time we salvaged if we need too
    DestroySalvageStats()

    for index, bonus in ipairs(itemData.bonus)
    do
        if( bonus.type == GameData.BonusTypes.SETBONUS_MAGIC and GetBonusIsSalvagable(itemData.level, bonus.reference) == 1)
        then
            local ref = bonus.reference
            if( CraftingUtils.GetSalvagingStatString(ref) ~= nil )
            then
                --DEBUG(L"Ref: "..ref..L" Label: "..CraftingUtils.GetSalvagingStatString[ref] )
                AddSalvageStat( ref, CraftingUtils.GetSalvagingStatString(ref) )
            end
        end
    end

    SalvagingWindow.selectedSlot = slotNum
    SalvagingWindow.selectedBackpack = backpackType
    if( itemData.flags[GameData.Item.EITEMFLAG_MAGICAL_SALVAGABLE] )
    then
        --DEBUG(L"Magical!")
        SalvagingWindow.salvagingType = GameData.SalvagingTypes.MAGICAL
    else
        --DEBUG(L"Mundane!")
        SalvagingWindow.salvagingType = GameData.SalvagingTypes.MUNDANE
    end
    
    if( SalvagingWindow.numStats > 1  and itemData.rarity ~= SystemData.ItemRarity.COMMON )
    then
        -- for the first stat added make sure to set its radio button as selected
        SalvagingWindow.selectedStat = WindowGetId( SalvagingWindow.radioButtons[1] )
        UpdateStatRadioButtons()
        
        -- resize the window
        SalvagingWindow.ResizeOnSelf()
        SalvagingWindow.EndSalvage()
        SalvagingWindow.Show()
    else
        --DEBUG(L"SalvagingWindow.selectedSlot: "..SalvagingWindow.selectedSlot..L" SalvagingWindow.salvagingType: "..SalvagingWindow.salvagingType..L" SalvagingWindow.selectedStat: "..SalvagingWindow.selectedStat)
        -- if there is a stat on the item to salvage then send the stat num
        if( SalvagingWindow.radioButtons[1] ~= nil )
        then
            SalvagingWindow.selectedStat = WindowGetId( SalvagingWindow.radioButtons[1] )
        end
        
        -- Set the action bar text if the salvaing was sent
        if( RequestSalvageItem( SalvagingWindow.selectedSlot, SalvagingWindow.selectedBackpack, SalvagingWindow.salvagingType, SalvagingWindow.selectedStat ) )
        then
            LayerTimerWindow.SetActionName( GetString( StringTables.Default.LABEL_SKILL_SALVAGING ), true )
        end
    end
end

function SalvagingWindow.ResizeOnSelf()
    local height = SalvagingWindow.WINDOW_BASE_HEIGHT + SalvagingWindow.STAT_CHOICE_HEIGHT * SalvagingWindow.numStats
    WindowSetDimensions( SalvagingWindow.windowName, SalvagingWindow.WINDOW_WIDTH, height )
end

function SalvagingWindow.OnRButtonUp()
    EA_Window_ContextMenu.CreateDefaultContextMenu( SalvagingWindow.windowName )
end

function SalvagingWindow.OnStatLButtonUp()
    SalvagingWindow.selectedStat = WindowGetId( WindowGetParent( SystemData.ActiveWindow.name ) )
    --DEBUG(L"SalvagingWindow.selectedStat: "..SalvagingWindow.selectedStat)
    UpdateStatRadioButtons()
end

function SalvagingWindow.OnRButtonProcessed()
    SalvagingWindow.EndSalvage()
end

function SalvagingWindow.OnLButtonProcessed()

    local winName = EA_BackpackUtilsMediator.GetBackpackWindowName()
    if winName ~= "" and string.sub(SystemData.MouseOverWindow.name,1,string.len(winName))==winName
    then
        return
    end
    
    SalvagingWindow.EndSalvage()
end

function SalvagingWindow.OnAcceptLButtonUp()
    if( RequestSalvageItem( SalvagingWindow.selectedSlot, SalvagingWindow.selectedBackpack, SalvagingWindow.salvagingType, SalvagingWindow.selectedStat ) )
    then
        LayerTimerWindow.SetActionName( GetString( StringTables.Default.LABEL_SKILL_SALVAGING ), true )
    end
    SalvagingWindow.Hide()
end

-- I don't believe SalvagingLootBag is used anymore so commenting out to see if anyone misses it -jmm 1/13/09
--[[

SalvagingLootBag = {}

SalvagingLootBag.windowName = "SalvagingLootBag"
SalvagingLootBag.lootItemInfo = nil
SalvagingLootBag.WINDOW_WIDTH = 375
SalvagingLootBag.WINDOW_BASE_HEIGHT = 100
SalvagingLootBag.ITEM_HEIGHT = 75
SalvagingLootBag.MAX_ITEMS = 10

function SalvagingLootBag.Initialize()
    WindowRegisterEventHandler( SalvagingLootBag.windowName, SystemData.Events.PLAYER_SALVAGING_LOOT_BAG_UPDATED, "SalvagingLootBag.UpdateLoot")
    LabelSetText(SalvagingLootBag.windowName.."TitleBarText", GetString( StringTables.Default.TEXT_SALVAGING_LOOT_CRATE ) )
    ButtonSetText( SalvagingLootBag.windowName.."LootAllButton", GetString( StringTables.Default.TEXT_SALVAGING_LOOT_CRATE_TAKE_ALL_ITEMS ) )
end

function SalvagingLootBag.Shutdown()
    
end

function SalvagingLootBag.Show()
    if( WindowGetShowing( SalvagingLootBag.windowName ) )
    then
        return
    end
    
    WindowSetShowing( SalvagingLootBag.windowName, true)
    
    WindowUtils.AddToOpenList( SalvagingLootBag.windowName )

    Sound.Play( Sound.WINDOW_OPEN )
    
end

function SalvagingLootBag.Hide()
    if( not WindowGetShowing( SalvagingLootBag.windowName ) )
    then
        return
    end

    WindowSetShowing( SalvagingLootBag.windowName, false )
    
    Sound.Play( Sound.WINDOW_CLOSE )
    
    WindowUtils.RemoveFromOpenList( SalvagingLootBag.windowName )
    
    EA_BackpackUtilsMediator.ReleaseAllLocksForWindow( SalvagingLootBag.windowName )
end

function SalvagingLootBag.UpdateLoot()
    SalvagingLootBag.lootItemInfo = GetSalvagingLootBagItems()
    EA_BackpackUtilsMediator.ReleaseAllLocksForWindow( SalvagingLootBag.windowName )
    EA_BackpackUtilsMediator.RequestLockForSlot( SalvagingLootBag.lootItemInfo.backpackSlot, EA_Window_Backpack.TYPE_INVENTORY, SalvagingLootBag.windowName )
    local lastIndex = 0
    local height = SalvagingLootBag.WINDOW_BASE_HEIGHT
    for index, itemData in ipairs( SalvagingLootBag.lootItemInfo.items )
    do
        local validItem = DataUtils.IsValidItem( itemData )

        WindowSetShowing( SalvagingLootBag.windowName.."Item"..index, validItem  )

        if( validItem )
        then
            local texture, x, y = GetIconData( itemData.iconNum )
            DynamicImageSetTexture( SalvagingLootBag.windowName.."Item"..index.."Icon", texture, x, y )
            
            LabelSetText( SalvagingLootBag.windowName.."Item"..index.."Text", itemData.name )
            
            local color = DataUtils.GetItemRarityColor(itemData)
            LabelSetTextColor( SalvagingLootBag.windowName.."Item"..index.."Text", color.r, color.g, color.b )
            
            height = height + SalvagingLootBag.ITEM_HEIGHT
            
            lastIndex = index
        end
    end
        
    for index = lastIndex + 1, SalvagingLootBag.MAX_ITEMS
    do
        WindowSetShowing( SalvagingLootBag.windowName.."Item"..index, false  )
    end

    WindowSetDimensions( SalvagingLootBag.windowName, SalvagingLootBag.WINDOW_WIDTH, height )

    if( lastIndex < 1 )
    then
        SalvagingLootBag.Hide()
    else
        SalvagingLootBag.Show()
    end
end

function SalvagingLootBag.OnItemRButtonUp()
    -- Take One Item
    local index = WindowGetId( SystemData.MouseOverWindow.name )
    TakeItemFromContainer( index )
end

function SalvagingLootBag.OnItemMouseOver()
    if( not SalvagingLootBag.lootItemInfo )
    then
        SalvagingLootBag.lootItemInfo = GetSalvagingLootBagItems()
    end
    
    local itemWindow = WindowGetParent( WindowGetParent( SystemData.MouseOverWindow.name ) )
    local index = WindowGetId( itemWindow )
    local item = SalvagingLootBag.lootItemInfo.items[index]
    if item ~= nil and item.uniqueId ~= 0 then
        Tooltips.CreateItemTooltip (item,
                                    SystemData.MouseOverWindow.name, 
                                    Tooltips.ANCHOR_WINDOW_LEFT, 
                                    true,
                                    nil, nil, true)
    end
end

function SalvagingLootBag.OnTakeAllLButtonUp()
    TakeItemFromContainer( -1 )
end
--]]

